package verify

import (
	"data/view/oplog"
	"data/view/user"
	"fmt"
	"public/message"
	"public/tools"

	"github.com/ant0ine/go-json-rest/rest"
)

//
var M_verify Verify

//
type Verify struct {
}

// var url string
// var appId string
// var app_secret string

// func init() {
// 	var data config.VerifyInfo = config.GetVerifyInfo()
// 	url = data.Url
// 	appId = data.AppId
// 	//tmp := mysign.GetOne(appId)
// 	//app_secret = tmp.App_secret
// 	app_secret = data.App_secret
// }

//获取验证码
func (v *Verify) GetVerify(w rest.ResponseWriter, r *rest.Request) {
	var req Req_verifyEx
	tools.GetRequestJsonObj(r, &req)

	//入口参数检测
	if !tools.CheckParam(req.Access_token, req.Phone) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	info := OnGet(req.Access_token)
	if len(info.Access_token) > 0 {
		w.WriteJson(message.GetErrorMsg(message.VerifyTimeError))
		return
	}

	//手机格式判断
	if !tools.IsPhone(req.Phone) {
		w.WriteJson(message.GetErrorMsg(message.PhoneParameterError))
		return
	}

	//判断手机号是否被绑定
	username := user.OnGetUserNameFromPhone(req.Phone)
	if req.Isnew {
		if len(username) > 0 {
			w.WriteJson(message.GetErrorMsg(message.ExistedError, "手机已被绑定"))
			return
		}
	} else {
		if len(username) == 0 {
			w.WriteJson(message.GetErrorMsg(message.ExistedError, "手机未绑定"))
			return
		}
	}
	//----------------------end

	var users user.User_tbl
	var b = false
	if len(req.Access_token) <= 11 {
		users.User = req.Access_token
		b = true
	} else {
		users, b = user.GetUserDetailFromToken(req.Access_token)
	}
	//判断用户是否过期
	if b {
		var info VerifyInfo
		info.Access_token = req.Access_token
		info.Phone = req.Phone
		info.Verify = fmt.Sprintf("%04d", tools.GetGetRandInt(0, 9999))
		if OnSendMsg(info.Phone, "verify", info.Verify) {
			OnAdd(info) //保存短信缓存
			var logs oplog.Op_log_tbl
			logs.Operator = users.User
			logs.Topic = "帐号系统"
			logs.Bundle = "验证码"
			logs.Pid = "获取"
			logs.Ip_addr = tools.GetClientIp(r.Request)
			logs.Attach0 = info.Phone
			oplog.OpLogBaseAdd(logs) //保存日志
			w.WriteJson(message.GetSuccessMsg())
		} else {
			w.WriteJson(message.GetErrorMsg(message.SMSSendFaild))
		}
	}
}

// func (v *Verify) GetVerify(w rest.ResponseWriter, r *rest.Request) {
// 	var req Req_verify
// 	tools.GetRequestJsonObj(r, &req)

// 	//入口参数检测
// 	if !tools.CheckParam(req.UserName, req.Lg) || req.Flag == 0 {
// 		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
// 		return
// 	}
// 	signature := tools.Md5Encoder(req.Lg + req.UserName + strconv.Itoa(req.Flag) + strconv.Itoa(req.Msgflag) + appId + app_secret)
// 	requestbody := RequestBody{req.Lg, req.UserName, req.Flag, appId, req.Msgflag, signature}
// 	//发送请求
// 	//	stb := &ResponseBody{}
// 	var mess message.MessageBody
// 	myhttp.SendPost(&requestbody, &mess, url)
// 	w.WriteJson(mess)
// 	return

// }
